package com.kgc.community.controller;

import com.github.pagehelper.PageInfo;
import com.kgc.community.pojo.RoomUser;
import com.kgc.community.pojo.Rooms;
import com.kgc.community.pojo.User;
import com.kgc.community.service.PersonnelService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author dingChangXiao
 * @create 2020-11-26  15:34  com.kgc.community.controller  null.java
 */
@RequestMapping("personnel")
@Controller
public class PersonnelController {
    @Resource
    PersonnelService personnelService;


    /**
     * 查询
     * @return personnel_list
     */
    @RequestMapping("query.do")
    public String selectAll(HttpServletRequest request, Model model) {
        Integer pageNum=1;
        if (request.getParameter("pageNum")!=null){
            pageNum=Integer.parseInt(request.getParameter("pageNum"));
        }
        String selectBy=request.getParameter("selectBy")==null?"":request.getParameter("selectBy");
        Integer pageSize=5;
        PageInfo<RoomUser> pageInfo = personnelService.selectAllPersonnel("%"+selectBy+"%", pageNum, pageSize);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("selectBy", selectBy);
        return "personnel_list";
    }


    /**
     * 删除单条
     * @return personnel_list
     */
    @RequestMapping("delete.do")
    @ResponseBody
    public String deletePersonnel(HttpServletRequest request) {
        Integer id = Integer.parseInt(request.getParameter("id"));
        int count = personnelService.deletePersonnel(id);
        if (count > 0) {
            return "{\"status\":\"1\"}";
        }
        return "{\"status\":\"2\"}";

    }


    /**
     * 批量删除
     * @return personnel_list
     */
    @RequestMapping("deleteAll.do")
    public String deleteAll(HttpServletRequest request, Model model) {
            String[] subs = request.getParameterValues("sub");
            int sum = 0;
            int count = 0;
            for (String sub : subs) {
                Integer id = Integer.parseInt(sub);
                count = personnelService.deletePersonnel(id);
                sum += count;
            }
            if (sum == subs.length & sum > 0) {
                model.addAttribute("deleteAllresult", true);
                return "forward:query.do";
            }
            model.addAttribute("deleteAllresult", false);
            return "forward:query.do";
    }

    /**
     * 进入添加页面
     * 查询用户号
     * @return personnel_add
     */
    @RequestMapping("inAdd.do")
    public String inAdd(Model model){

        List<Rooms> rooms = personnelService.selectRoomsId();
        model.addAttribute("rooms", rooms);
        return "personnel_add";
    }


    @RequestMapping("image.do")
    @ResponseBody
    public Map<String, Object> addImage(Model model,@RequestParam("images") MultipartFile images,  HttpSession session) {
        Map<String, Object> modelMap=new HashMap<String, Object>();
        /*验证文件大小和格式*/
        int size=555*1024;
        if (images.getSize()>size){
            modelMap.put("msg", "文件最大不能超过555K");
            return modelMap;
        }
        List<String> list=new ArrayList<>();
        list.add("jpg");
        list.add("png");
        list.add("jpeg");
        list.add("gif");
        //获取文件上传路径
        String realPath = session.getServletContext().getRealPath("images/uploadfiles/");
        //源文件名
        String oldName=images.getOriginalFilename();
        //扩展名
        String extension = FilenameUtils.getExtension(oldName);
        if (list.contains(extension)==false){
            modelMap.put("msg", "不支持"+extension+"此格式");
            return modelMap;
        }
        //获取文件名（生成一个新的文件名）
        String newName=System.currentTimeMillis()+ new Random().nextInt(1000)+"_id_pic."+extension;
        System.out.println("名字"+newName);
        //封装File对象
        File file=new File(realPath,newName);
        //实现上传
        try {
            images.transferTo(file);
            modelMap.put("msg", "文件上传成功");
            modelMap.put("id_pic", newName);
            modelMap.put("status", "1");
            return modelMap;
        } catch (IOException e) {
            e.printStackTrace();
            modelMap.put("status", "2");
            return modelMap;
        }

    }



    /**
     * 添加
     * @return
     */
    @RequestMapping("add.do")
    public String add(HttpServletRequest request, Model model){
        Map<String, String[]> map = request.getParameterMap();
        User user = new User();
        RoomUser roomUser = new RoomUser();
        Rooms room = new Rooms();
        try {
            BeanUtils.populate(user, map);
            BeanUtils.populate(roomUser, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Integer userId=(int)System.currentTimeMillis();
        Integer status = Integer.parseInt(request.getParameter("status"));
        String roomId = request.getParameter("roomId");
        user.setId(userId);
        user.setRoleId(status);
        roomUser.setUserId(userId);
        room.setId(roomId);
        room.setStatus(1);
        int count = personnelService.addPersonnel(user,roomUser,room);
        if (count > 0) {
            model.addAttribute("addResult", true);
            return "forward:query.do";
        }
        model.addAttribute("addResult", false);
        return "forward:query.do";

    }

    /**
     * 修改
     * @return personnel_modify
     */
    @RequestMapping("selectPersonnel.do")
    public String select(HttpServletRequest request, Model model) {
        /*房间号select*/
        List<Rooms> rooms = personnelService.selectRoomsId();
        model.addAttribute("rooms", rooms);
        /*查询其他信息*/
        Integer roomUserId = Integer.parseInt(request.getParameter("id"));
        RoomUser roomUser = personnelService.selectPersonnel(roomUserId);
        model.addAttribute("personnel", roomUser);
        return "personnel_modify";
    }



    @RequestMapping("modify.do")
    public String modify(HttpServletRequest request, Model model){
        Map<String, String[]> map = request.getParameterMap();
        User user = new User();
        RoomUser roomUser = new RoomUser();
        try {
            BeanUtils.populate(user, map);
            BeanUtils.populate(roomUser, map);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Integer status = Integer.parseInt(request.getParameter("status"));
        Integer id = Integer.parseInt(request.getParameter("id"));
        Integer userId = Integer.parseInt(request.getParameter("userId"));
        user.setRoleId(status);
        user.setId(userId);
        roomUser.setId(id);

        int count = personnelService.modifyPersonnel(user,roomUser);
        if (count > 0) {
            model.addAttribute("modifyResult", true);
            return "forward:query.do";
        }
        model.addAttribute("modifyResult", false);
        return "forward:query.do";

    }

}
